package com.gm.wholesale.bluetooth.view;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import com.gm.commonlib.base.baseAdapter.CommonAdapter;
import com.gm.commonlib.base.baseAdapter.ViewHolder;
import com.gm.commonlib.util.logUtils.LogUtil;
import com.gm.commonlib.views.popupwindow.Popupwindow;
import com.gm.wholesale.R;
import com.gm.wholesale.bluetooth.BluetoothUtil;
import com.gm.wholesale.bluetooth.bean.DeviceBean;


import java.util.ArrayList;
import java.util.List;
public class BlueDeviceListView extends LinearLayout {
    private Context mContext;
    private ListView mListView;

    private TextView ntTv;
    private List<DeviceBean> mDevices = new ArrayList<>();
    private CommonAdapter mAdapter;
    private OnBlueDeviceChoiceListener listener;

    public void setOnBlueDeviceChoiceListener(OnBlueDeviceChoiceListener listener) {
        this.listener = listener;
    }

    public interface OnBlueDeviceChoiceListener {
        void choiceBlue(DeviceBean device);
    }


    public BlueDeviceListView(Context context) {
        super(context);
        initView(context);
    }

    public BlueDeviceListView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.view_blue_device_list, this);
        mListView = findViewById(R.id.listView);
        ntTv = findViewById(R.id.ntTv);
        findViewById(R.id.closeImage).setOnClickListener(view -> {
            Popupwindow.hiddenPop();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
                    BluetoothUtil.newInstance().cancelDiscovery(context);
                }
            } else {
                BluetoothUtil.newInstance().cancelDiscovery(context);
            }


        });

    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                        showNotPermission();
                        return;
                    }
                }
                if (device==null)return;
                String deviceName = device.getName();
                LogUtil.d("getAddress: " + device.getAddress());
                LogUtil.d("name: " + device.getName());
                if (!TextUtils.isEmpty(deviceName)) {
                    if (mFilter == null || mFilter.isEmpty()) {
                        DeviceBean deviceBean = new DeviceBean();
                        deviceBean.setAddress(device.getAddress());
                        deviceBean.setName(device.getName());
                        addDevice(deviceBean);
                        showDeviceListView();

                    } else if (mFilter.size() == 1) {
                        if (mFilter != null && deviceName.startsWith(mFilter.get(0))) {
                            setDevice(context, device);
                        }
                    } else {
                        boolean find = false;
                        for (String filter : mFilter) {
                            if (mFilter != null && deviceName.startsWith(filter)) {
                                find = true;
                                break;
                            }
                        }
                        if (find) {
                            setDevice(context, device);
                        }
                    }

                }

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (mDevices.size() == 0) {
                    ntTv.setText("没有发现设备");
                    ntTv.setVisibility(VISIBLE);
                } else {
                    showDeviceListView();
                }
            }
        }
    };

    private void setDevice(Context context, BluetoothDevice device) {
        DeviceBean deviceBean = new DeviceBean();
        deviceBean.setAddress(device.getAddress());
        BluetoothUtil.setDevice(context,device,deviceBean);
        addDevice(deviceBean);
        showDeviceListView();
    }

    private void addDevice(DeviceBean deviceBean) {
        if (mDevices.isEmpty()) {
            mDevices.add(deviceBean);
            return;
        }
        boolean isExit = false;
        for (DeviceBean deviceBean1 : mDevices) {
            if (deviceBean1.getName().equals(deviceBean.getName())) {
                isExit = true;
                break;
            }
        }
        if (!isExit) {
            mDevices.add(deviceBean);
        }
    }

    private List<String> mFilter;

    public void startFindDevice(List<String> filter) {
        mFilter = filter;
        ntTv.setText("正在搜索设备...");
        ntTv.setVisibility(VISIBLE);
        BluetoothUtil.newInstance().startFindDevice(mContext, mReceiver);


    }


    private synchronized void showDeviceListView() {

        //  List<DeviceBean> devices=new ArrayList<>();
        // devices.addAll(mDevices);
        if (mDevices != null && !mDevices.isEmpty()) {
            ntTv.setText("发现设备");
            ntTv.setVisibility(VISIBLE);
        }
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
            return;
        }

        mAdapter = new CommonAdapter<>(mContext, mDevices, R.layout.list_item_unit) {

            @Override
            public void convert(ViewHolder viewHolder, DeviceBean device) {
                viewHolder.setText(R.id.unitTv, device.getName());
                viewHolder.getConvertView().setOnClickListener(view -> {
                    if (listener != null) {
                        listener.choiceBlue(device);
                    }

                });
            }
        };
        mListView.setAdapter(mAdapter);
    }

    private void showNotPermission() {
        Popupwindow.hiddenPop();
        BluetoothUtil.showNotPermiss();
    }
}
